<template>
    <div class="table-page">
        <GiTable
            ref="tableRef"
            row-key="id"
            title="地址管理"
            :data="dataList"
            :columns="columns"
            :loading="loading"
            :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
            :pagination="false"
            :disabled-tools="['size']"
            :disabled-column-keys="['name']"
            @refresh="search"
        >
            <template #expand-icon="{ expanded }">
                <IconDown v-if="expanded"/>
                <IconRight v-else/>
            </template>
            <template #toolbar-left>
                <a-input v-model="name" placeholder="请输入名称" allow-clear @change="search">
                    <template #prefix>
                        <icon-search/>
                    </template>
                </a-input>
                <a-button @click="reset">
                    <template #icon>
                        <icon-refresh/>
                    </template>
                    <template #default>重置</template>
                </a-button>
            </template>
            <template #toolbar-right>
                <a-button v-permission="['system:dept:add']" type="primary" @click="onAdd('0')">
                    <template #icon>
                        <icon-plus/>
                    </template>
                    <template #default>新增</template>
                </a-button>
                <!--        <a-button v-permission="['system:dept:export']" @click="onExport">-->
                <!--          <template #icon><icon-download /></template>-->
                <!--          <template #default>导出</template>-->
                <!--        </a-button>-->
            </template>
            <template #action="{ record }">
                <a-space>
                    <a-link v-permission="['system:provinceCityArea:modify']" @click="onUpdate(record)">修改</a-link>
                    <a-link v-permission="['system:provinceCityArea:create']" @click="onAdd(record.id)">新增</a-link>
                    <a-link
                        v-permission="['system:provinceCityArea:delete']"
                        status="danger"
                        @click="onDelete(record)"
                    >
                        删除
                    </a-link>
                </a-space>
            </template>
        </GiTable>

        <AddressAddModal ref="AddressAddModalRef" @save-success="search"/>
    </div>
</template>

<script setup lang="ts">
import AddressAddModal from './AddressAddModal.vue'
import {type AddressQuery, type AddressDto, deleteAddress, exportAddress, listAddress} from '@/apis/system/address'
import type GiTable from '@/components/GiTable/index.vue'
import type {TableInstanceColumns} from '@/components/GiTable/type'
import {useDownload, useTable} from '@/hooks'
import {isMobile} from '@/utils'
import has from '@/utils/has'

defineOptions({name: 'SystemAddress'})
const tableRef = ref<InstanceType<typeof GiTable>>()
const queryForm = reactive<AddressQuery>({})
const {
    tableData,
    loading,
    search,
    handleDelete
} = useTable(() => listAddress(queryForm), {
    immediate: true,
    onSuccess: () => {
        nextTick(() => {
            tableData.value = getTreeData(tableData.value);
            tableRef.value?.tableRef?.expandAll(true)
        })
    }
})

// 递归方法
const getTreeData = (data:any)=> {
    // 循环遍历json数据
    for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            delete data[i].children;
        } else {
            // children若不为空数组，则继续 递归调用 本方法
            getTreeData(data[i].children);
        }
    }
    return data;
}

// 过滤树
const name = ref('')
const searchData = (name: string) => {
    const loop = (data: AddressDto[]) => {
        const result = [] as AddressDto[]
        data.forEach((item: AddressDto) => {
            if (item.name?.toLowerCase().includes(name.toLowerCase())) {
                result.push({...item})
            } else if (item.children) {
                const filterData = loop(item.children)
                if (filterData.length) {
                    result.push({
                        ...item,
                        children: filterData
                    })
                }
            }
        })
        return result
    }
    return loop(tableData.value)
}

const dataList = computed(() => {
    if (!name.value) return tableData.value
    return searchData(name.value)
})

const columns: TableInstanceColumns[] = [
    {title: '城市名稱', dataIndex: 'name', width: 170, ellipsis: true, tooltip: true},
    {title: '创建人', dataIndex: 'createUserString', ellipsis: true, tooltip: true, show: false},
    {title: '创建时间', dataIndex: 'createTime', width: 180},
    {title: '修改人', dataIndex: 'updateUserString', ellipsis: true, tooltip: true, show: false},
    {title: '修改时间', dataIndex: 'updateTime', width: 180, show: false},
    {
        title: '操作',
        slotName: 'action',
        width: 180,
        align: 'center',
        fixed: !isMobile() ? 'right' : undefined,
        show: has.hasPermOr(['system:provinceCityArea:modify', 'system:provinceCityArea:delete', 'system:provinceCityArea:add'])
    }
]

// 重置
const reset = () => {
    name.value = ''
}

// 删除
const onDelete = (record: AddressDto) => {
    return handleDelete(() => deleteAddress(record.id), {
        content: `是否确定删除 [${record.name}]？`,
        showModal: true
    })
}

// 导出
const onExport = () => {
    useDownload(() => exportAddress(queryForm))
}

const AddressAddModalRef = ref<InstanceType<typeof AddressAddModal>>()
// 新增
const onAdd = (parentId?: string) => {
    AddressAddModalRef.value?.onAdd(parentId)
}

// 修改
const onUpdate = (record: AddressDto) => {
    AddressAddModalRef.value?.onUpdate(record)
}
</script>

<style lang="scss" scoped></style>
